package com.cf.web.filter;


import com.cf.web.autoconfigure.WebCommonProperty;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * boot-awm-ZmmFilter
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/7/6 下午 01:16
 */
public abstract class ZmmFilter implements Filter {

    @Autowired
    public WebCommonProperty webCommonProperty;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String requestURI = httpServletRequest.getRequestURI();
        if (ignore(requestURI)) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            doInnerFilter((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse, filterChain);
        }
    }

    @Override
    public void destroy() {

    }

    protected abstract void doInnerFilter(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException;

    /**
     * 需要拦截的地址
     *
     * @return
     */
    public abstract List<String> matchPathPatterns();

    protected boolean ignore(String path) {
        List<String> ignores = webCommonProperty.getIgnore();
        if (ignores == null)
            return true;

        for (String ignore : ignores) {
            boolean start = path.startsWith(ignore);
            if (start)
                return start;
        }

        return false;
    }
}
